<?php

namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page; 

class PresaleController extends BaseController {
	function _initialize() {
		parent::_initialize ();
	}

	public function index(){
        $this->display();
    }

//获取预售团购内容
    public function presaleList()
    {
  
    $_listrows = I('request._listrows', '', 'trim');
        $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['g.goods_sn|g.goods_name']=array('like',"%{$keywords}%");
        }
       $type = I('request.blongtype',-1,'intval');
		if( $type != -1){
			if($type==1){
				$blongtype = 'presell';
			}else{
				$blongtype = 'group';
			}
			$_where['a.blongtype']=$blongtype;
		} 
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');
        $str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
        if(!(empty($start_time) && empty($end_time))){ 
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }  
  
           $str =" and a.addtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'"; 
        }  
        
        $str = ltrim(trim($str),'and');
        if(!empty($str)){
            $_where['_string']=$str;
        }
    $where_order['where'] = $_where;
        /*$where_order['order'] = ' last_transaction_time desc ';*/
        $where_order['listrows'] = $_listrows;
        $where_order["id"]="load_tb_div";
        $where_order["alias"]="a";
        $where_order["order"]="a.addtime desc";
        $where_order["field"]="a.*,g.goods_name,g.goods_sn,u.user_name";
        $where_order["join"]=array('inner join '.$this->dbprefix.'goods g on a.goodsid=g.goods_id',' inner join '.$this->dbprefix.'admin_user u on a.adminuserid=u.user_id');   

        $_datalist = $this->_getListsFromModel('group_purchase', $where_order);
    

        $this->assign('_datalist', $_datalist);
        $this->display(); 
 

    }

//添加团购商品
public function add_group(){
	//$blongtype = I('request.blongtype', '', 'trim');
	$this->assign('blongtype','group');
    $this->display();

}
//添加预售商品
public function add_presell(){
	//$blongtype = I('request.blongtype', '', 'trim');
	$this->assign('blongtype','presell');
    $this->display();

}	


//添加商品
 public function  goods_list(){
 	    $blongtype = I('request.blongtype', '', 'trim');
 	    $_listrows = I('request._listrows', '', 'trim');
		$keywords = I('request.keywords','','trim');
		$_where="";
		if(!empty($keywords)){
			//$keywords = str_replace("'", '\'', $keywords);
		   //$_where['goods_name|goods_sn']=array('like',"%{$keywords}%");
		   $_where .='(a.goods_name like "%'.$keywords.'%" or a.goods_sn like "%'.$keywords.'%") and ';
		} 
		//$_where.=" is_delete = 0 and is_on_sale = 1 and goods_number > warn_number and is_general=1";
        $_where .=" a.is_delete = 0 and a.is_general=1";
		//团购设置必须为上架的商品
		if($blongtype == 'group'){
			$_where  .= " and a.is_on_sale=1 ";
		}
        //商品没有删除的
		$where_order['where'] = $_where;
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div"; 
		$where_order["field"]="a.goods_id,a.goods_sn,a.goods_weight,a.shop_price,a.first_price,a.sale_price,REPLACE(a.goods_name,'\'','’') AS goods_name";
		$where_order['alias']="a";
		$where_order['order']="a.goods_id asc";
		/*$where_order["join"] =array(' INNER JOIN `'.$this->dbprefix.'category` c ON a.cat_id=c.cat_id');*/
		
        $_datalist = $this->_getListsFromModel('Goods', $where_order);
  
		//echo M('Goods')->getLastSql();
		//die;
        //查询改订单是否有赠品 
        $sqllist = D('group_purchase')->where("blongtype ='".$blongtype."'" )->select();
         if(!empty($sqllist)){
            $this->assign('sqllist',json_encode($sqllist));
         }
        $this->assign('blongtype',$blongtype);
      	$this->assign('_datalist', $_datalist);
		$this->display('goods_list');
 }	




 public function add_goods(){
  $ret=array('staute'=>'error','msg'=>"保存失败");
		$blongtype=I("blongtype");
		$postdata=I("json");
		
		if(empty($blongtype)||empty($postdata)){
			$ret=array('staute'=>'error','msg'=>"传输参数错误");
			$this->ajaxReturn ($ret);
			exit;
		} 
		
		$json = json_decode($postdata,true); 
		if(!is_array($json)){
			$ret=array('staute'=>'error','msg'=>"商品信息错误");
			$this->ajaxReturn ($ret);
			exit;
		}
		//对数据进行处理
		 $sl=M("group_purchase");
		 $where['blongtype'] = $blongtype;
		 $dblist= $sl->where($where)->select(); //数据库当前主题存在的记录信息;
		 
		 $aryadd=$arydel=$aryupd=array();
		 //提交数据 是否在数据库中存在，存在更新否则增加
		 foreach($json as $k=>$v){ 
		 	$flg=0;
		 	foreach ($dblist as $key=>$o){ 
		 	  if( $o["blongtype"]==$blongtype && $v["goodsid"]==$o['goodsid']){
		 	  	  $aryupd[]=$v;		
		 	  	  $flg=1;
		 	  	  break;
		 	  }
		 	}
		   if($flg==0){
		   	    $v["blongtype"]=$blongtype;
		     	$aryadd[]=$v;
		   }
		 }
		 
		 //在数据库里存在，但是提交的数据不存在，删除数据
		 foreach ($dblist as $key=>$o){
		 	$bl=0;
		 	foreach($json as $k=>$v){
		 	  if($o['blongtype']==$blongtype && $v["goodsid"]==$o['goodsid']){ 
		 			$bl=1;
		 			break;
		 		}
		 	}
		 	if($bl==0){
		 		$arydel[]=$o;
		 	}
		 }
		  
		 $sqladd=$sqlupd=$sqldel="";
		 $arysqlupd=array();  
		 $time=date("Y-m-d H:i:s");
		 


		 //构建插入数据语句
		 if(count($aryadd)>0){
		 	$sqlval=""; 
		 	foreach ($aryadd as $k=>$v){
		 		$listid=getGuid();//创建guid值
		 		$sqlval.=((empty($sqlval)?"":",")."('$listid','".$v['goodsid']."','".$blongtype."','$time',".UID.")");
		 	}
		 	$sqladd=" INSERT INTO  ".$this->dbprefix."group_purchase(`id`,`goodsid`,`blongtype`,`addtime`,`adminuserid`) values ".$sqlval;
		 }
		 
		 //构建更新数据语句
/*		 if(count($aryupd)>0){  
		 	foreach ($aryupd as $k=>$v){
		 		$money = intval($v['number'])*$v['price'] + $v['logistics_price']*$v['weight'];
		 		$sqlupd="update ".$this->dbprefix."wx_parcellist set parcelid='$parcel',pb_id='".$v['pb_id']."',goodsid='".$v['goodsid']."',goodsname='".$v['goodsname']."',price='".$v['price']."',unit='".$v['unit']."',logistics_price='".$v['logistics_price']."',weight='".$v['weight']."',money='".$money."',operationuser='".UID."',createtime='".$time."' where listid='".$v['listid']."'";
		 		$arysqlupd[]=$sqlupd;
		 	} 
		 }*/
		
		 //构建删除数据语句
		 if(count($arydel)>0){
		 	$sqlval="";
		 	foreach ($arydel as $k=>$v){
		 		$sqlval.=((empty($sqlval)?"":",").$v['id']);
		 	}
		 	if(!empty($sqlval))
		 	   $sqldel="delete from ".$this->dbprefix."group_purchase where FIND_IN_SET(id,'".$sqlval."')";
		 }
		 
		 $db=M("group_purchase");
		 $retadd=$retupd= $retdel=1; //默认是成功状态
		 
		 $db->startTrans(); //启动事务
		 
		 if($sqladd){
		    $retadd=$db->execute($sqladd);
		 } 
		 
		 if($sqldel){
		    $retdel=$db->execute($sqldel);
		 }
		 
		 if($retadd  && $retdel){
		    $db->commit();
		    $ret=array('staute'=>'success','msg'=>"保存数据成功");
		 }
		 else {
		    $db->rollback();
		    $ret=array('staute'=>'error','msg'=>"保存数据失败");
		 }  
		$this->ajaxReturn($ret);

 }



 public function delete_wx_presale(){
     if(IS_GET){
        $map['id'] = I('get.id');
        //判断该商品是否在团里面，如果存在就不能删除
       $res  =  D("group_purchase")->where($map)->find();
       if(!$res){
         $this->error("删除失败");
       }
       $where['goodsid'] = $res['goodsid'];
       $where['blongtype'] = $res['blongtype'];
       $sql = D('group_package_goods')->where($where)->find();
       if(empty($sql) || !isset($sql)){
       	        $row = D('group_purchase')->where($map)->delete();
			        if($row != flase){
			        	$this->success("删除成功") ;
			        }else{
			        	$this->error("删除失败") ;
			        }
	 }else{
         $this->success("该商品已近在包里面，不能删除！") ;
	  }


     }
 }

 //批量删除
 public function all_delete_wx_presale(){
     if(IS_POST){
        $allid = I('post.allid');
        $arrid = explode(',',$allid);
        $tmp = array();
        $res = array();
        foreach ($arrid as $key => $value) {
          $res  =  D("group_purchase")->where("id = ".$value)->find();
             $where['goodsid'] = $res['goodsid'];
		     $where['blongtype'] = ucfirst($res['blongtype']);
		     
		     $sql = D('group_package_goods')->where($where)->find();

		     if(empty($sql) || !isset($sql)){
		     	array_push($tmp,$value);
		     }
        }
      
        $_arr_id = implode(',',$tmp );
        if($_arr_id != ""){
	        $where = "id in (".$_arr_id.")";
	        $row = D('group_purchase')->where($where)->delete();
	           if($row != flase){
	           	if(count($tmp) < count($arrid)){
                        $ret=array('staute'=>'success','msg'=>"批量删除成功!,有些包中的商品不能删除！");
	           	}else{
	           		 $ret=array('staute'=>'success','msg'=>"批量删除成功!");
	           	}
        	        
		        }else{
		        	 $ret=array('staute'=>'error','msg'=>"批量删除失败");
		       }
        }else{
            $ret=array('staute'=>'success','msg'=>"所有的商品都在包中，不能删除！");
        }

        //echo D('group_purchase')->getLastSql();

     $this->ajaxReturn($ret);

 }

}
}
?>
